package com.cqndt.disaster.device.sys.service.impl;

import com.cqndt.disaster.device.sys.dao.SysMenuMapper;
import com.cqndt.disaster.device.sys.dao.SysRoleMapper;
import com.cqndt.disaster.device.sys.dao.SysUserMapper;
import com.cqndt.disaster.device.sys.service.SysMenuService;
import com.cqndt.disaster.device.sys.shiro.ShiroUtils;
import com.cqndt.disaster.device.sys.vo.SysMenuVo;
import com.cqndt.disaster.device.util.Constant;
import com.cqndt.disaster.device.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    private static final Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class);
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<Map<String, Object>> navigationList(String userId, String frontBack) {
        //超级管理员
        if(userId.equals(Constant.SUPER_ADMIN.toString())){
            return getAllMenuList(null,frontBack);
        }
        return getAllMenuList(userId,frontBack);
    }
    /**
     * 获取所有菜单列表
     */
    private List<Map<String,Object>> getAllMenuList(String userId, String frontBack){
        //查询根菜单列表
        List<Map<String,Object>> menuList;
        if(null == userId){
            menuList = sysMenuMapper.queryMenuForAdmin(frontBack,"0");
        }else{
            menuList = sysMenuMapper.queryMenuForUser(userId,frontBack,"0");
        }
        //递归获取子菜单
        getMenuTreeList(menuList,frontBack,userId);
        return menuList;
    }
    /**
     * 递归
     */
    private List<Map<String,Object>> getMenuTreeList(List<Map<String,Object>> menuList,String frontBack,String userId){
        List<Map<String,Object>> subMenuList = new ArrayList<Map<String,Object>>();
        for(Map<String,Object> map : menuList){
            //目录
            if("0".equals(map.get("hassub"))||0 == Integer.valueOf(map.get("hassub").toString())){
                List<Map<String,Object>> list;
                if(null == userId){
                    list = sysMenuMapper.queryMenuForAdmin(frontBack,map.get("id").toString());
                }else{
                    list = sysMenuMapper.queryMenuForUser(userId,frontBack,map.get("id").toString());
                }
                map.put("children",getMenuTreeList(list,frontBack,userId));
            }else{
                map.put("children",new ArrayList<Map<String,Object>>());
            }
            subMenuList.add(map);
        }
        return subMenuList;
    }
    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void save(SysMenuVo sysMenuVo) throws Exception {
        if(null == sysMenuVo.getParentId() || (sysMenuVo.getParentId()+"") == ""){
            sysMenuVo.setParentId(0);
        }
        if(null!=sysMenuVo.getHassub()){
            sysMenuVo.setType("0".equals(sysMenuVo.getHassub())?"1":"2");
        }
        //如果父类为倾斜摄影，则type为100
        SysMenuVo menu = sysMenuMapper.getTabMenuById(sysMenuVo.getParentId()+"");
        if(null != menu && ("100").equals(menu.getType())){
            sysMenuVo.setType("100");
            //TODO tab_photography表新增一条？
        }
        sysMenuMapper.save(sysMenuVo);
        //如果为无下级，则增加增删改查权限
        if("1".equals(sysMenuVo.getHassub().toString())){
            this.saveButton(sysMenuVo);
        }
        //当前用户增加菜单则分配菜单给当前用户的角色
        Long userId = ShiroUtils.getUserId();
        String roleId = sysUserMapper.getRoleIdByUserId(userId);
        sysRoleMapper.saveTabRoleMenu(roleId,sysMenuVo.getId().toString());
    }
    //按钮增加
    private void saveButton(SysMenuVo sysMenuVo){
        SysMenuVo vo = new SysMenuVo();
        vo.setFrontBack(sysMenuVo.getFrontBack());
        vo.setParentId(sysMenuVo.getId());
        vo.setStatus(0);
        vo.setHassub(1);
        vo.setType("3");
        //如果为后台菜单，则有增删改权限
        if("1".equals(sysMenuVo.getFrontBack())){
            vo.setPerms("sys:"+sysMenuVo.getPerms()+":save");
            vo.setName("增加");
            sysMenuMapper.save(vo);
            vo.setId(null);
            vo.setPerms("sys:"+sysMenuVo.getPerms()+":update");
            vo.setName("修改");
            sysMenuMapper.save(vo);
            vo.setId(null);
            vo.setPerms("sys:"+sysMenuVo.getPerms()+":delete");
            vo.setName("删除");
            sysMenuMapper.save(vo);
        }
        vo.setId(null);
        vo.setPerms("sys:"+sysMenuVo.getPerms()+":list");
        vo.setName("查看");
        sysMenuMapper.save(vo);
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void update(SysMenuVo sysMenuVo){
        sysMenuMapper.update(sysMenuVo);
    }
    @Override
    public SysMenuVo getTabMenuById(String id){
        return sysMenuMapper.getTabMenuById(id);
    }

    @Override
    public Result delete(String id){
        List<SysMenuVo> vo1 = sysMenuMapper.getTabMenuSub(id);
        if(null != vo1 && vo1.size()>0){
            return new Result().failure(-1,"菜单还有下级菜单不能进行删除");
        }
        SysMenuVo vo = sysMenuMapper.getTabMenuById(id);
        //删除菜单（物理删除）
        vo.setStatus(1);
        sysMenuMapper.update(vo);
        //如果是子菜单,则删除对应的菜单按钮
        if("1".equals(vo.getHassub())){
            sysMenuMapper.deleteMenuButton(id);
        }
        //删除关联表信息
        sysMenuMapper.deleteTabRoleMenu(id);
        return new Result().success("删除成功");
    }

    @Override
    public Result checkData(SysMenuVo sysMenuVo) {
        Result result = new Result();
        //如果无子级则path为空
        if("1".equals(sysMenuVo.getHassub())&& (null == sysMenuVo.getPath()||("").equals(sysMenuVo.getPath()))){
            return result.failure(-1,"菜单url不能为空");
        }
        //父级是否有子节点，有才能进行菜单增加
        if(null != sysMenuVo.getParentId()){
            SysMenuVo voParent = sysMenuMapper.getTabMenuById(sysMenuVo.getParentId()+"");
            if(null !=voParent && "1".equals(voParent.getHassub())){
                return result.failure(-1,"父级不为目录菜单,不能添加子菜单");
            }
        }
        //菜单名称不能重复
        boolean flag = false;
        if(null != sysMenuVo.getId()){
            SysMenuVo vo = sysMenuMapper.getTabMenuById(sysMenuVo.getId()+"");
            flag = vo.getName().equals(sysMenuVo.getName());
        }
        //验证菜单名称的唯一性
        if (!flag){
            SysMenuVo vo = new SysMenuVo();
            vo.setName(sysMenuVo.getName());
            List<SysMenuVo> voList = sysMenuMapper.list(vo);
            if (voList.size()>0){
                return result.failure(-1,"菜单名称不能重复");
            }
        }
        return result.success();
    }

    @Override
    public List<SysMenuVo> list(SysMenuVo sysMenuVo) {
        return  sysMenuMapper.list(sysMenuVo);
    }
    @Override
    public List<Map<String,Object>> listTabMenu(SysMenuVo sysMenuVo){
        return  sysMenuMapper.listTabMenu(sysMenuVo);
    }

    @Override
    public List<SysMenuVo> listTabRoleAll(SysMenuVo sysMenuVo){
        return  sysMenuMapper.listTabRoleAll(sysMenuVo);
    }

    @Override
    public List<SysMenuVo> listTabRoleSelect(Integer id){
        return  sysMenuMapper.listTabRoleSelect(id);
    }

    @Override
    public List<Map<String, Object>> listTabStaticType(SysMenuVo sysMenuVo) {
        return sysMenuMapper.listTabStaticType(sysMenuVo);
    }

}